//
//  NFindDetailViewController.m
//  News
//
//  Created by zhangtao on 2018/11/4.
//  Copyright © 2018年 zt.td. All rights reserved.
//

#import "NFindDetailViewController.h"
#import "NFindDetailTopCell.h"
#import "NFindDetailBottomView.h"
#import "UIButton+NBtnBadge.h"

@interface NFindDetailViewController ()<WKUIDelegate,WKNavigationDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *table;
@property(nonatomic,strong)WKWebView *wkWeb;
@property(nonatomic,assign)CGFloat wkwebH;

@property(nonatomic,strong)NFindDetailBottomView *bottomView;

@property(nonatomic,assign)NSInteger CommentNum;
@property(nonatomic,strong)NSString *Content;

@end

@implementation NFindDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0,*)) {
        self.table.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ACEWidth, ACEHeight-tabBarHeight) style:UITableViewStyleGrouped];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.table];
    [self.table registerNib:[UINib nibWithNibName:@"NFindDetailTopCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
    
    _bottomView = [[NFindDetailBottomView alloc]initWithFrame:CGRectMake(0, ACEHeight-tabBarHeight, ACEWidth, tabBarHeight)];
    [self.view addSubview:_bottomView];

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, tabBarHeight/2-14, 28, 28)];
    [btn setImage:[UIImage imageNamed:@"48-48slh"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"48-48slh"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick)];
 
    [self requestArticle];
}

-(void)requestArticle{
    NSDictionary *param = @{@"acode":_article.Code,@"cuid":CUID};
    [[NHTTPManage shareInstance]afGet:HTTP_ARTICLE_DETAIL andParam:param success:^(id  _Nonnull responseObject) {
        NSLog(@"");
        self.CommentNum = [responseObject[@"Data"][@"CommentNum"] integerValue];
        self.Content = responseObject[@"Data"][@"Content"];
    } failture:^(id  _Nonnull error) {
        NSLog(@"");
    }];
}

-(void)setCommentNum:(NSInteger)CommentNum{
    _CommentNum = CommentNum;
    [_bottomView.msgBtn badgeNum:_CommentNum andFont:10];
}

-(void)setContent:(NSString *)Content{
    
     NSString *zshead = @"<html><head><meta content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" name=\"viewport\"><style type=\"text/css\">img{display: inline-block;max-width: 100%}</style></head><body>";
    
    _Content = [zshead stringByAppendingString:Content];
//    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:_Content]];
//    [_wkWeb loadRequest:request];
    [_wkWeb loadHTMLString:_Content baseURL:nil];
}

-(void)rightClick{
    
}

-(WKWebView *)wkWeb{
    if (!_wkWeb) {
        [ACEPublicTool showToastActivity];
        _wkWeb = [[WKWebView alloc]initWithFrame:self.view.bounds];
        //    [self.view addSubview:_wkWeb];
//        [_wkWeb loadHTMLString:[self html] baseURL:nil];
        
        _wkWeb.UIDelegate = self;
        _wkWeb.navigationDelegate = self;
        //        _wkWeb.scrollView.scrollEnabled = NO;
    }
    return _wkWeb;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 0 ?2 :1;  //3
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 && indexPath.row == 0) {
         CGSize size = [ACEPublicTool textViewTextFont: [UIFont boldSystemFontOfSize:30] andText:_article.Title Weight:ACEWidth-20 andHeight:1000];
        return size.height;
    }
    
    if (indexPath.section == 0 && indexPath.row == 1) {
        return 50;
    }
    
    if (indexPath.section == 1) {
        return self.wkWeb.frame.size.height;
    }
    
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return .1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .1;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        CGSize size = [ACEPublicTool textViewTextFont: [UIFont boldSystemFontOfSize:30] andText:_article.Title Weight:ACEWidth-20 andHeight:1000];
        
        UITableViewCell *cell = [[UITableViewCell alloc]initWithFrame:CGRectMake(0, 0, ACEWidth, size.height)];
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSeparatorStyleNone;
        
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, ACEWidth-20, size.height)];
        lab.text = _article.Title;
        [cell addSubview:lab];
        lab.font = [UIFont boldSystemFontOfSize:30];
        lab.numberOfLines = 0;
        return cell;
    }else if (indexPath.section == 0 && indexPath.row == 1){
        NFindDetailTopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topCell"];
        cell.article = _article;
        cell.foceOrCancelBtn = ^(UIButton * _Nonnull btn) {
            if (btn.selected == YES) {
                //取消关注
                [self fouceOrCancel:NO];
            }else{
                //关注
                [self fouceOrCancel:YES];
            }
        };
        
        if (_isFocue) {
            cell.focusBtn.selected = YES;
        }else{
            cell.focusBtn.selected = NO;
        }
        return cell;
    }else if(indexPath.section == 1){
        UITableViewCell *cell = [[UITableViewCell alloc]init];
        [cell addSubview:self.wkWeb];
        return cell;
    }
    return nil;
}

-(void)fouceOrCancel:(BOOL)isFouce{
    NSDictionary *param = @{@"token":TOKEN,@"cuid":CUID,@"tid":_article.TopicalID};
    NSString *url = @"";
    if (isFouce == YES) {
        url = HTTP_FOLLOW_TOPICAL;
    }else{
        url = HTTP_DELETE_TOPICAL;
    }
    
    [[NHTTPManage shareInstance]afPOST:url andParam:param success:^(id  _Nonnull responseObject) {
        NSLog(@"..");
    } failture:^(id  _Nonnull error) {
        NSLog(@"...");
        [ACEPublicTool showToastInWindow:error];
    }];
}



//  页面开始加载web内容时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [ACEPublicTool showToastActivity];
}

//  当web内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
}

//  页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [ACEPublicTool hidenToastActivity];
    //    CGFloat webViewHeight=[webView.scrollView contentSize].height;
    //    CGRect newFrame = webView.frame;
    //    newFrame.size.height = webViewHeight;
    //    webView.frame = CGRectMake(0, 0, LEPWidth, webViewHeight);
    //    self.wkwebH = webViewHeight;
    //    [self.table reloadData];
    
    
    
    WEAKSELF;
    [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
        
        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
        
        CGFloat f = heightStr.floatValue;
        CGFloat webViewHeight=[webView.scrollView contentSize].height;
        
        weakSelf.wkwebH = webViewHeight;
        
        weakSelf.wkWeb.frame = CGRectMake(0, 0, ACEWidth, webViewHeight);
        [weakSelf.table reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        [ACEPublicTool hidenToastActivity];
    }];
    
    
}

//  页面加载失败时调用 ( 【web视图加载内容时】发生错误)
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
}

// 【web视图导航过程中发生错误】时调用。
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
}

// 当Web视图的Web内容进程终止时调用。
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    
}


@end
